package railRoad.db;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

import org.apache.log4j.Logger;
import org.h2.jdbcx.JdbcConnectionPool;

import railRoad.exception.OpenFileException;

//Singelton
/**
 * Class that creates database connection pool
 */
public class DBConectionPool {

	private static DBConectionPool instance = new DBConectionPool();

	private static final Logger LOGGER = Logger.getLogger(DBConectionPool.class
			.getName());

	private JdbcConnectionPool connectionPool = null;
	private Properties properties;

	public static DBConectionPool getInstance() {
		return instance;
	}

	private DBConectionPool() {
		properties = new Properties();
	}

	/**
	 * Method that return connection to DB from pool
	 * 
	 * @return connection from connection pool
	 * @throws SQLException
	 */
	public Connection getConnection() throws SQLException {
		Connection connection = null;
		if (connectionPool != null)
			connection = connectionPool.getConnection();
		return connection;
	}

	public void close(Connection conn) {
		// System.out.println("destroying connection!");

		if (conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				// System.out.println(e.getMessage());
				LOGGER.error(e);
			}// catch
		}// if
	}// close()

	/**
	 * Method to create open connection pool
	 * 
	 * @param login
	 * @param pass
	 * @throws OpenFileException
	 */
	public void open(String login, String pass) throws OpenFileException {
		try {
			properties.load(DBReader.class
					.getResourceAsStream("/db.properties"));

			Class.forName(properties.getProperty("driver"));

			connectionPool = JdbcConnectionPool.create(
					properties.getProperty("url"), login, pass);

			connectionPool.setMaxConnections(Integer.parseInt(properties
					.getProperty("max_connection")));
			
			LOGGER.info("DBConectionPool: database open");
		}// try
		catch (IOException e) {
			throw new OpenFileException(e.getMessage());
		}// catch (IOException e)
		catch (ClassNotFoundException e) {
			// System.out.println(e.getMessage());
			// e.printStackTrace();
			LOGGER.error(e);
		}// catch (ClassNotFoundException e)
	}// open

	/**
	 * close connection pool
	 * 
	 * @throws SQLException
	 */
	public void close() throws SQLException {
		connectionPool.dispose();
		
		LOGGER.info("DBConectionPool: database close");
		// System.out.println("cp.getActiveConnections() = " +
		// connectionPool.getActiveConnections());
	}// close
}
